package gold.digger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC18 {
    public List<List<Integer>> threeSumWithTarget(int[] nums, int start, int target) {
        // Arrays.sort(nums);  //排序
        List<List<Integer>> re = new ArrayList<List<Integer>>();

        for (int i = start; i < nums.length - 2; ++i) {
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }

            int twoSumTarget = target - nums[i];
            List<List<Integer>> twoSumResult = twoSumWithTarget(nums, i + 1, twoSumTarget);
            if (twoSumResult.size() > 0) {
                for (List<Integer> reEle : twoSumResult) {
                    reEle.add(nums[i]);
                }
            }
            re.addAll(twoSumResult);
        }

        return re;
    }

    public List<List<Integer>> twoSumWithTarget(int[] nums, int start, int target) {
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        int lb = start, ub = nums.length - 1;
        while (lb < ub) {
            int curMinus = target - nums[lb] - nums[ub];
            if (curMinus == 0) {
                List<Integer> curAns = new ArrayList<>();
                curAns.add(nums[lb]);
                curAns.add(nums[ub]);
                re.add(curAns);
                ++lb;
                --ub;
            } else if (curMinus > 0) {
                ++lb;
            } else {
                --ub;
            }

            while (lb > start && lb < nums.length && nums[lb] == nums[lb - 1]) ++lb;
            while (ub < nums.length - 1 && ub >= start && nums[ub] == nums[ub + 1]) --ub;
        }

        return re;
    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        if (null == nums || nums.length <= 3) {
            return new ArrayList<List<Integer>>();
        }

        Arrays.sort(nums);  //排序
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        for (int i = 0; i < nums.length - 3; ++i) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int threeSumTarget = target - nums[i];
            List<List<Integer>> threeSumResult = threeSumWithTarget(nums, i + 1, threeSumTarget);
            if (threeSumResult.size() > 0) {
                for (List<Integer> reEle : threeSumResult) {
                    reEle.add(nums[i]);
                }
            }

            re.addAll(threeSumResult);
        }
        return re;
    }

    public static void main(String[] args) {
        LC18 an = new LC18();
        int[] nums = {-1, 2, 2, -5, 0, -1, 4};
        int target = 3;
        System.out.println(an.fourSum(nums, target));
    }
}
